﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;

namespace DAL
{
    public class EnumHelperDic
    {
        /// <summary>  
        /// 枚举转字典集合  
        /// </summary>  
        /// <typeparam name="T">枚举类名称</typeparam>  
        /// <param name="value">默认value值</param>  
        /// <param name="text">默认text值</param>  
        /// <returns>返回生成的字典集合</returns>  
        public static dynamic EnumListDic<T>(int valueDefault = 0, string textDefault = "--请选择--")
        {
            List<dynamic> dicEnum = new List<dynamic>();
            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                return dicEnum;
            }
            if (valueDefault == 0) //判断是否添加默认选项  
            {
                dicEnum.Add(new { value = valueDefault, text = textDefault });
            }
            string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组  
            foreach (var item in fieldstrs)
            {
                string description = string.Empty;
                var field = enumType.GetField(item);
                object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组  
                if (arr != null && arr.Length > 0)
                {
                    description = ((DescriptionAttribute)arr[0]).Description;   //属性描述  
                }
                else
                {
                    description = item;  //描述不存在取字段名称  
                }
                dicEnum.Add(new { value = (int)Enum.Parse(enumType, item), text = description });//不用枚举的value值作为字典key值的原因从枚举例子能看出来，其实这边应该判断他的值不存在，默认取字段名称  
            }
            return dicEnum;
        }

        /// <summary>
        /// </summary>
        /// <param name="State"></param>
        /// <returns></returns>
        public static string GetEnumSelectState<T>(int State)
        {
            string description = string.Empty;

            Type enumType = typeof(T);
            string[] fieldstrs = Enum.GetNames(enumType); //获取枚举字段数组  
            foreach (var item in fieldstrs)
            {
                if (State == (int)Enum.Parse(enumType, item))
                {
                    var field = enumType.GetField(item);
                    object[] arr = field.GetCustomAttributes(typeof(DescriptionAttribute), true); //获取属性字段数组  
                    if (arr != null && arr.Length > 0)
                    {
                        description = ((DescriptionAttribute)arr[0]).Description;   //属性描述  
                    }
                    else
                    {
                        description = item;  //描述不存在取字段名称  
                    }
                    break;
                }
            }
            return description;
        }
    }
}